package com.bw.common.view

import android.content.Intent
import android.os.Bundle
import androidx.databinding.ViewDataBinding
import com.bw.base.view.BaseFragment
import com.bw.common.event.CustomEvent
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

abstract class BaseMvvmFragment<VDB:ViewDataBinding>:BaseFragment<VDB>() {



    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //获取数据
        loadData()
        //订阅数据
        observeDataChanged()
        //EventBus事件总线
        EventBus.getDefault().register(this)
    }

    //接收事件
    @Subscribe(threadMode =  ThreadMode.MAIN)
    public fun onReceiveEvent(event: CustomEvent?){
        //校验是否为当前接收事件
        if (event != null && event.target == this.javaClass.simpleName){
            handEvent(event)
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        //反注册，防止内存溢出
        EventBus.getDefault().unregister(this)
    }



    protected open fun startNextActivity(intent: Intent?){
        intent?.run {
            startActivity(this)
        }
    }

    protected open fun startNextActivityForResult(intent: Intent?, requestCode:Int){
        intent?.run{
            startActivityForResult(this,requestCode)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        receiveNextForResult(requestCode,resultCode, data)
    }

    protected open fun receiveNextForResult(requestCode:Int,resultCode:Int, data: Intent?){

    }

    //可以根据业务需要重写方法
    protected open fun loadData(){}

    //可以根据业务需要重写方法
    protected open fun observeDataChanged(){}

    //交给子类处理事件
    protected open fun handEvent(event: CustomEvent){

    }
}